<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
        integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

    <title>碧蓝航线CD计算器-舰娘配置</title>
    <style>
        img.head {
            width: 80px;
            height: 80px;
            border-radius: 10px;
        }

        .hide {
            display: none !important;

        }

        .click-target {
            cursor: pointer;
        }

        .align-middle {
            float: none;
            display: inline-block;
            vertical-align: middle;
        }

        #alert {
            display: block;
            position: fixed;
            top: 10px;
            left: 5%;
            width: 90%;
            z-index: 2000;
        }

        div.ship {
            margin: 10px 0 10px 0;
        }
    </style>
</head>

<body>
    <div class="container text-center">
        <h1>碧蓝航线CD计算器-舰娘配置</h1>

        <div class="mb-3 row align-items-center">
            <div class="col-2" style="height: 80px;">
                <div class="thumbnail click-target">
                    <img id="cur-ship-img" class="head" data-toggle="modal" data-target="#ship-modal" src="">
                </div>
            </div>
            <div class="col-2">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ship-modal">
                    选择舰娘
                </button>
            </div>

            <div class="col-2">
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ship-templates-modal">
                    添加新舰娘
                </button>
            </div>

        </div>
        <div id="ship-modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-body">
                        <div class="md-3 row">
                            <div class="col-12">
                                <input type="text" class="form-control" id="ship-filter"
                                    placeholder="请输入舰娘名称(支持模糊搜索/拼音)">
                            </div>
                        </div>
                        <br>
                        <div id="ships" class="md-3 row"></div>
                    </div>
                </div>
            </div>
        </div>
        <div id="ship-templates-modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-body">
                        <div class="md-3 row">
                            <div class="col-12">
                                <input type="text" class="form-control" id="ship-template-filter"
                                    placeholder="请输入舰娘名称(支持模糊搜索/拼音)">
                            </div>
                        </div>
                        <br>
                        <div id="ship-tempaltes" class="md-3 row"></div>
                    </div>
                </div>
            </div>
        </div>
        <label class="mb-3 row">
            <div class="col-sm-2">
                名称
            </div>
            <div class="col-sm-10">
                <input class="form-control" type="text" name="ship-name" id="name">
            </div>
        </label>
        <div class="mb-3 row">
            <div class="col-sm-2 col-form-label">
                输入方式
            </div>
            <div class="btn-group" data-toggle="buttons">
                <label class="btn btn-secondary active">
                    <input type="radio" name="mode" value="auto">自动计算
                </label>
                <label class="btn btn-secondary">
                    <input type="radio" name="mode" value="manual" checked>手动输入
                </label>
            </div>
        </div>
        <div class="ship-inputs ship-inputs-auto">
            <div class="mb-3 row">
                <div class="col-sm-2">
                    好感度
                </div>
                <div class="btn-group" data-toggle="buttons">
                    <label class="btn btn-secondary">
                        <input type="radio" name="love" value="1">失望/陌生
                    </label>
                    <label class="btn btn-secondary">
                        <input type="radio" name="love" value="1.01">友好
                    </label>
                    <label class="btn btn-secondary">
                        <input type="radio" name="love" value="1.03">喜欢
                    </label>
                    <label class="btn btn-secondary">
                        <input type="radio" name="love" value="1.06" checked>爱
                    </label>
                    <label class="btn btn-secondary">
                        <input type="radio" name="love" value="1.09">誓约
                    </label>
                    <label class="btn btn-secondary">
                        <input type="radio" name="love" value="1.12">誓约200
                    </label>
                </div>
            </div>

            <label class="mb-3 row input-group input-group-sm">
                <div class="col-sm-2 col-form-label">
                    等级
                </div>
                <div class="col-sm-10">
                    <input class="form-control" type="number" name="level" id="level" value="120" min="1" max="120">
                </div>
            </label>
        </div>
        <div class="ship-inputs ship-inputs-manual">
            <label class="mb-3 row input-group input-group-sm">
                <div class="col-sm-2 col-form-label">
                    装填
                </div>
                <div class="col-sm-10">
                    <input class="form-control" type="number" name="reload" id="reload">
                </div>
            </label>
        </div>
        <label class="mb-3 row input-group input-group-sm">
            <div class="col-sm-2 col-form-label">
                装备
            </div>
            <div class="col-sm-10 col-form-label" id="slots">
            </div>
        </label>

    </div>
    <div id="alert" class="alert alert-danger" style="display: none;"></div>
    <template id="panel">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-primary">
                    <div class="panel-body">
                        <div class="col-sm-6 col-md-4">
                            <div class="thumbnail">
                                <img src="">
                                <div class="caption">
                                    <h3></h3>
                                    <button class="btn btn-danger">删除</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
        integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuidv4.min.js"></script>
    <script src="js/storage.js?v=5"></script>
    <script>
        let enums = {};
        let allShip = loadAllShips();
        let curIdx = getCurrentShipIdx();
        function saveData() {
            console.log('saveAllShips');
            saveAllShips(allShip);
            setCurrentShipIdx(curIdx);
        }
        window.addEventListener('beforeunload', saveData);
        let shipBasicData = {};
        function bindFilter(filter, target) {
            $(filter).keyup(function () {
                var ipt = $(filter);
                var term = $.trim(ipt.val());
                term = term.replace(/'/g, '').toLowerCase();
                if (ipt.data('lastTerm') === term) {
                    return;
                }
                ipt.data('lastTerm', term);
                console.log('apply filter', filter, term);
                $(target).each((idx, elem) => {
                    var elem = $(elem);
                    if (term === '') {
                        elem.removeClass('hide');
                        return;
                    }
                    var text = elem.data('match') || elem.text();
                    if (text.indexOf(term) > -1) {
                        elem.removeClass('hide');
                        return;
                    }
                    elem.addClass('hide');
                })
            });
        }
        bindFilter('#ship-filter', '#ships > .ship');
        bindFilter('#ship-template-filter', '#ship-tempaltes > .ship-template');

        $('div.modal').on('shown.bs.modal', function (e) {
            $(this).find('input')[0].focus();
            console.log('focus on', $(this).find('input')[0]);
        })
        var alertHandle;
        function makeAlert(text) {
            if (alertHandle) {
                clearTimeout(alertHandle);
            }
            $('#alert').text(text);
            $('#alert').show();
            alertHandle = setTimeout(function () {
                $('#alert').hide();
                alertHandle = null;
            }, 1500);
        }
        function checkForShipExist() {
            if (allShip.length === 0) {
                makeAlert('舰娘列表为空, 请添加舰娘');
                $('#ship-templates-modal').modal('show');
            }
            selectShip(curIdx);
        }
        $('#ship-templates-modal').on('hidden.bs.modal', checkForShipExist);

        function addShip(idx, ship) {
            $('#ships').append(`
                <div class="col-sm-3 col-md-2 ship" data-match="${shipBasicData[ship.id].match}">
                    <div class="thumbnail text-center">
                        <div class="click-target" onclick="selectShip(${idx})" 
                            data-idx="${idx}" draggable="true" ondragstart="markDrag(event)">
                            <img class="head" draggable="false" src="images/headers/${shipBasicData[ship.id].img}"
                                data-idx="${idx}" ondragover="onDragOver(event)" ondrop="moveShip(event)">
                            <br>
                            ${ship.name}
                        </div>
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteShip(${idx})">删除</button>
                    </div>
                </div>
            `);
        }
        function markDrag(ev) {
            // Add the target element's id to the data transfer object
            ev.dataTransfer.setData("text", $(ev.target).data('idx'));
            console.log(ev, ev.target);
        }
        function onDragOver(ev) {
            ev.preventDefault();
            ev.dataTransfer.dropEffect = "move";
        }
        function moveShip(ev) {
            ev.preventDefault();
            window.ev = ev;
            console.log(ev);
            var idx = parseInt(ev.dataTransfer.getData("text")), newIdx = parseInt($(ev.target).data('idx'));
            console.log('Move', idx, newIdx);
            if (isNaN(idx) || isNaN(newIdx)) {
                return;
            }
            var item = allShip.splice(idx, 1)[0];
            allShip.splice(newIdx, 0, item);
            reloadShip();
        }
        function deleteShip(idx) {
            if (allShip.length === 1) {
                makeAlert('无法删除最后一个舰娘!');
                return;
            }
            allShip.splice(idx, 1);
            reloadShip();
            // 需要更新lastTerm, 才能触发filter
            $('#ship-filter').data('lastTerm', '')
            $('#ship-filter').keyup();
            if (curIdx === idx) {
                selectShip(0, false);
            }
            // return false;
        }

        function selectShipTemplate(obj) {
            var id = $(obj).data('id');
            console.log('选择舰娘', id, $(obj).attr('title'));
            curIdx = allShip.length;
            var ship = {
                id: id,
                uuid: uuidv4(),
                name: shipBasicData[id].名称,
                type: shipBasicData[id].type,
                mode: 'auto',
                level: 120,
                love: 1.06,
            };
            allShip.push(ship);
            $('#ship-templates-modal').modal('hide');
            addShip(curIdx, ship);
            selectShip(curIdx);
        }

        function selectShip(idx, hide = true) {
            curIdx = idx;
            var ship = allShip[curIdx];
            console.log('选择舰娘', ship);
            if (hide) {
                $('#ship-modal').modal('hide');
            }
            // 图片
            $('#cur-ship-img').attr('src', 'images/headers/' + shipBasicData[ship.id].img);
            // 名称
            $('#name').val(ship.name);
            // 等级
            $('#level').val(ship.level);
            if (!shipBasicData[ship.id].args) {
                // 无数据, 强制使用手动输入
                ship.mode = 'manual';
                $('input[name=mode][value=manual]').click();
                $('input[name=mode]').prop('disabled', true);
            } else {
                $('input[name=mode]').prop('disabled', false);
                // 模式
                $('input[name=mode][value=' + ship.mode + ']').click();
                // 好感度
                $('input[name=love][value="' + ship.love + '"]').click();
            }
            // 装填
            if (ship.mode === 'auto') {
                updateReload();
            } else {
                $('#reload').val(ship.reload);
            }
            var slots = shipBasicData[ship.id].slots;
            var text = [];
            for (var idx in slots) {
                var types = [];
                for (var t of slots[idx].type) {
                    types.push(enums.EQUIP_TYPE[t]);
                }
                text.push(types.join('/') + '*' + slots[idx].cnt)
            }
            $('#slots').text(text.join('; '));
        }

        $('input[name=mode]').change(function () {
            var val = $('input[name=mode]:checked').val();
            console.log('show', val);
            allShip[curIdx].mode = val;
            if (val === 'manual') {
                $('div.ship-inputs-auto').hide();
                $('div.ship-inputs-manual input').prop('disabled', false);
            } else {
                updateReload();
                $('div.ship-inputs-auto').show();
                $('div.ship-inputs-manual input').prop('disabled', true);
            }
        });
        // 根据属性计算装填值
        function updateReload() {
            var ship = allShip[curIdx];
            ship.level = parseFloat($('#level').val());
            ship.love = parseFloat($('input[name=love]:checked').val());
            var r = shipBasicData[ship.id].args;
            // 装填白值 = (基础值 + 基础成长值 * (等级-1) / 1000 + 额外成长值 * (等级-100) / 1000 + 强化属性) * 好感度加成 + 改造属性
            ship.reload = (r[0] + r[1] * (ship.level - 1) / 1000 + r[2] * (ship.level - 100) / 1000 + r[3]) * ship.love + r[4];
            ship.reload = parseInt(ship.reload)
            $('div.ship-inputs-manual input').val(parseFloat(ship.reload));
        }
        $('div.ship-inputs-auto input').change(updateReload);
        $('#name').change(function () {
            allShip[curIdx].name = $(this).val();
            reloadShip();
        })
        function saveShip() {
            localStorage.setItem(STORE_KEYS.ship,);
        }
        function initShip(id) {
            var conf = shipBasicData[id];
            if (!conf.reloadAttr) {
                $('input[name=mode][value=manual]')[0].checked = true;
            }
        }
        function reloadShip() {
            $('#ships').html('');
            for (var [idx, ship] of allShip.entries()) {
                addShip(idx, ship);
            }
        }
        async function loadDataFromJson(url) {
            let resp = await fetch(url);
            let data = await resp.json();
            return data;
        }

        // In your Javascript (external .js resource or <script> tag)
        $(document).ready(async function () {
            enums = await loadDataFromJson('data/enums.json');
            let data = await loadDataFromJson('data/ships-simple.json?v=2');
            for (let ship of data) {
                shipBasicData[ship.编号] = ship;
                $('#ship-tempaltes').append(`
                    <div class="col-2 ship-template" data-match="${ship.match}">
                        <div class="thumbnail text-center click-target" onclick="selectShipTemplate(this)" data-id="${ship.编号}">
                            <div class="caption">
                                <img class="head" src="images/headers/${ship.img}">
                                <p>${ship.名称}</p>
                            </div>
                        </div>
                    </div>
                `);
                //  <img class="d-inline-flex head" src="images/headers/${ship.img}" 
                //  data-id="${ship.编号}" data-match="${ship.match}" title="${ship.名称}" alt="${ship.名称}"
                //  onclick="selectShipTemplate(this)"
                //  >
            }
            reloadShip();
            checkForShipExist();
        });
    </script>
</body>

</html>